<?php

namespace App\Http\Controllers\Order;

use App\Http\Controllers\Controller;
use App\Http\Requests\Order\OrderRequest;
use App\Models\Order\Order;
use App\Repositories\Order\OrderRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use App\Models\Common\EntityData\Channel\Sp;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;

class OrderController extends Controller
{
    use ModelForm;

    /** @var  OrderRepository */
    private $orderRepository;

    public function __construct(OrderRepository $orderRepo)
    {
        $this->orderRepository = $orderRepo;
    }

    /**
     * Display a listing of the Order.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('order.orders.index_header'));
            $content->description(__('order.orders.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new Order.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('order.orders.create_header'));
            $content->description(__('order.orders.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Order in storage.
     *
     * @param OrderRequest $request
     *
     * @return Response
     */
    public function store(OrderRequest $request)
    {
        $input = $request->all();

        $order = $this->orderRepository->create($input);

        Flash::success(__('order.orders.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('order.orders.index'));

    }

    /**
     * Display the specified Order.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $order = $this->orderRepository->findWithoutFail($id);

        if (empty($order)) {
            Flash::error(__('order.orders.not_found'));

            return redirect(route('order.orders.index'));
        }

        return view('order.orders.show')->with('order', $order);

    }

    /**
     * Show the form for editing the specified Order.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('order.orders.edit_header'));
            $content->description(__('order.orders.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Order in storage.
     *
     * @param  int              $id
     * @param OrderRequest $request
     *
     * @return Response
     */
    public function update($id, OrderRequest $request)
    {
        $order = $this->orderRepository->findWithoutFail($id);

        if (empty($order)) {
            Flash::error(__('order.orders.not_found'));

            return redirect(route('order.orders.index'));
        }

        $order = $this->orderRepository->update($request->all(), $id);

        Flash::success(__('order.orders.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('order.orders.index'));
    }

    /**
     * Remove the specified Order from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->orderRepository->batchDelete('id', $id)) {
                return response()->json(['message' => __('order.orders.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $order = $this->orderRepository->findWithoutFail($id);

        if (empty($order)) {
            Flash::error(__('order.orders.not_found'));

            return redirect(route('order.orders.index'));
        }

        if ($flag = $this->orderRepository->delete($id)) {

            return response()->json(['message' => __('order.orders.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Order::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('oprator_name', '局方名称');
            $form->text('sp_name', '服务商');
            $form->text('order_no', '商户订单号');
            $form->number('amount', '支付金额');
            $form->radio('pay_state', '支付结果')->options([
                0 => '失败',
                1 => '成功',
                2 => '其他未知',
            ])->default(0);
            $form->radio('is_support_reconciliation', '是否支持对账')->options([
                0 => '否',
                1 => '是',
            ])->default(0);
            $form->text('vasseti_name', '媒资名称');
            $form->radio('price_type', '定价类型')->options([
                1 => '产品包定价',
                2 => '单点定价',
            ])->default(1);
            $form->text('mac', '机顶盒MAC地址');
            $form->text('card_id', '智能卡号');
            $form->text('content_id', '内容ID');
            $form->radio('result', '包月订购结果')->options([
                0 => '成功',
                1 => '失败',
                2 => '报停',
                3 => '不可点播',
                4 => '基础包或功能关闭，请咨询96766',
                5 => '余额不足',
                6 => '其他',
            ]);
            $form->textarea('description', '结果描述');
            $form->text('service_code', '服务code');
            $form->radio('service_type', '服务类型')->options([
                1 => '按次(24小时免鉴权)',
                2 => '包月',
                3 => '(预留)',
                4 => '试看',
                5 => '按次(无24小时免鉴权)',
            ])->default(1);

            $form->display('created_at', __('base.created_at'));
            $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(Order::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            $grid->model()->orderBy('created_at', 'desc');

            // // 添加按钮
            // if (!\Gate::check('order.orders.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('order.orders.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('order.orders.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('order.orders.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('order.orders.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('order.orders.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('order.orders.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('order.orders.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('order.orders.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('order.orders.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('oprator_name', '局方名称')->sortable();
            $grid->column('sp_name', '服务商')->sortable();
            $grid->column('order_no', '商户订单号')->sortable();
            $grid->column('amount', '支付金额')->sortable();
            $grid->column('pay_state', '支付结果')->display(function ($val) {
                $display = '';
                switch ($val) {
                    case 0:
                        $display = '<span class="label label-danger">失败</span>';
                        break;
                    case 1:
                        $display = '<span class="label label-success">成功</span>';
                        break;
                    default:
                        $display = '<span class="label label-warning">未知</span>';
                        break;
                }
                return $display;
            })->sortable();
            $grid->column('is_support_reconciliation', '是否支持对账')->display(function ($val) {
                $display = '';
                switch ($val) {
                    case 0:
                        $display = '<span class="label label-danger">否</span>';
                        break;
                    case 1:
                        $display = '<span class="label label-success">是</span>';
                        break;
                }
                return $display;
            })->sortable();
            $grid->column('vasseti_name', '媒资名称')->sortable();
            $grid->column('price_type', '定价类型')->display(function ($val) {
                $display = '';
                switch ($val) {
                    case 1:
                        $display = '产品包定价';
                        break;
                    case 2:
                        $display = '单点定价';
                        break;
                }
                return $display;
            })->sortable();
            $grid->column('mac', '机顶盒MAC地址')->sortable();
            $grid->column('card_id', '智能卡号')->sortable();
            $grid->column('content_id', '内容ID')->sortable();
            $grid->column('result', '包月订购结果')->display(function ($val) {
                $display = '';
                switch ($val) {
                    case 0:
                        $display = '成功';
                        break;
                    case 1:
                        $display = '失败';
                        break;
                    case 2:
                        $display = '报停';
                        break;
                    case 3:
                        $display = '不可点播';
                        break;
                    case 4:
                        $display = '基础包或功能关闭，请咨询96766';
                        break;
                    case 5:
                        $display = '余额不足';
                        break;
                    default:
                        $display = '其他';
                        break;
                }
                return $display;
            })->sortable();
            $grid->column('service_code', '服务code')->sortable();
            $grid->column('service_type', '服务类型')->display(function ($val) {
                $display = '';
                switch ($val) {
                    case 1:
                        $display = '按次(24小时免鉴权)';
                        break;
                    case 2:
                        $display = '包月';
                        break;
                    case 3:
                        $display = '(预留)';
                        break;
                    case 4:
                        $display = '试看';
                        break;
                    case 5:
                        $display = '按次(无24小时免鉴权)';
                        break;
                }
                return $display;
            })->sortable();
            $grid->column('created_at', '创建时间')->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();

                // 订单号
                $filter->like('order_no', '商户订单号');
                // 局方名称
                $filter->like('vasseti_name', '媒资名称');
                // 创建时间
                $filter->between('created_at', '订单创建时间')->datetime();
                // 是否支持对账
                $filter->equal('is_support_reconciliation', '是否支持对账')->radio([
                    0 => '否',
                    1 => '是',
                ]);
                // SP名称
                $filter->like('sp_name', 'SP名称');
                // 局方名称
                $filter->like('oprator_name', '局方名称');
                // 支付金额
                $filter->between('amount', '支付金额');
                // 支付结果
                $filter->equal('pay_state', '支付结果')->radio([
                    0 => '失败',
                    1 => '成功',
                    2 => '其他未知',
                ]);
            });
        });
    }
}
